#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
N2浅睡眠状态分析问题诊断脚本

分析当前N2浅睡眠判断条件是否合理，
检查为什么会出现异常的浅睡眠识别
"""

import sys
import os

# 添加项目根目录到路径
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, current_dir)

from service.BrainStateService import BrainStateService
from models.brain_state_models import BrainWaveRatesInput

def analyze_log_data():
    """
    分析日志中的实际数据
    """
    print("=== N2浅睡眠状态分析问题诊断 ===")
    print()
    
    # 从日志中提取的实际数据样本
    log_samples = [
        {
            'description': '日志样本1 - 被识别为N2浅睡眠',
            'data': {'delta': 0.1651, 'theta': 0.4905, 'alpha': 0.1807, 'beta': 0.1243, 'gamma': 0.0394},
            'expected_state': 'n2_light_sleep',
            'confidence': 0.8371
        },
        {
            'description': '日志样本2 - 被识别为困倦状态',
            'data': {'delta': 0.1552, 'theta': 0.5249, 'alpha': 0.1678, 'beta': 0.1154, 'gamma': 0.0367},
            'expected_state': 'drowsy',
            'confidence': 0.8439
        },
        {
            'description': '日志样本3 - 被识别为REM睡眠',
            'data': {'delta': 0.1430, 'theta': 0.3520, 'alpha': 0.2462, 'beta': 0.2024, 'gamma': 0.0565},
            'expected_state': 'rem_sleep',
            'confidence': 0.5104
        },
        {
            'description': '日志样本4 - 被识别为N3深度睡眠',
            'data': {'delta': 0.3061, 'theta': 0.2286, 'alpha': 0.2471, 'beta': 0.1648, 'gamma': 0.0533},
            'expected_state': 'n3_deep_sleep',
            'confidence': 0.4415
        }
    ]
    
    # 创建BrainStateService实例，使用5频域模式
    service = BrainStateService(use_8_bands=False)
    
    print("1. 当前N2浅睡眠判断条件分析：")
    n2_conditions = service.STATE_RULES_5BAND['n2_light_sleep']['conditions']
    print(f"   - Theta波范围: {n2_conditions.get('theta_min', 0)} - {n2_conditions.get('theta_max', 1)}")
    print(f"   - Delta波范围: {n2_conditions.get('delta_min', 0)} - {n2_conditions.get('delta_max', 1)}")
    print(f"   - Alpha波上限: {n2_conditions.get('alpha_max', 1)}")
    print(f"   - Beta波范围: {n2_conditions.get('beta_min', 0)} - {n2_conditions.get('beta_max', 1)}")
    print(f"   - Gamma波上限: {n2_conditions.get('gamma_max', 1)}")
    print()
    
    print("2. 实际日志数据分析：")
    for i, sample in enumerate(log_samples, 1):
        print(f"\n样本{i}: {sample['description']}")
        print(f"   数据: {sample['data']}")
        print(f"   预期状态: {sample['expected_state']} (置信度: {sample['confidence']})")
        
        # 检查是否符合N2浅睡眠条件
        data = sample['data']
        n2_match = check_n2_conditions(data, n2_conditions)
        print(f"   符合N2条件: {n2_match}")
        
        # 重新分析这个数据
        from datetime import datetime
        current_time = datetime.now()
        input_data = BrainWaveRatesInput(
            session_id="analysis_test",
            start_time=current_time,
            end_time=current_time,
            relative_rates={
                'delta': [data['delta']],
                'theta': [data['theta']],
                'alpha': [data['alpha']],
                'beta': [data['beta']],
                'gamma': [data['gamma']]
            }
        )
        
        result = service.classify_brain_state(input_data)
        print(f"   重新分析结果: {result.state} (置信度: {result.confidence:.4f})")
        
        if result.state != sample['expected_state']:
            print(f"   ⚠️  分析结果不一致！")
    
    print("\n3. 问题分析：")
    analyze_n2_conditions_issues()
    
    print("\n4. 建议的修复方案：")
    suggest_fixes()

def check_n2_conditions(data, conditions):
    """
    检查数据是否符合N2浅睡眠条件
    """
    checks = []
    
    # Theta波检查
    theta_min = conditions.get('theta_min', 0)
    theta_max = conditions.get('theta_max', 1)
    theta_ok = theta_min <= data['theta'] <= theta_max
    checks.append(f"Theta({data['theta']:.4f}) in [{theta_min}, {theta_max}]: {theta_ok}")
    
    # Delta波检查
    delta_min = conditions.get('delta_min', 0)
    delta_max = conditions.get('delta_max', 1)
    delta_ok = delta_min <= data['delta'] <= delta_max
    checks.append(f"Delta({data['delta']:.4f}) in [{delta_min}, {delta_max}]: {delta_ok}")
    
    # Alpha波检查
    alpha_max = conditions.get('alpha_max', 1)
    alpha_ok = data['alpha'] <= alpha_max
    checks.append(f"Alpha({data['alpha']:.4f}) <= {alpha_max}: {alpha_ok}")
    
    # Beta波检查
    beta_min = conditions.get('beta_min', 0)
    beta_max = conditions.get('beta_max', 1)
    beta_ok = beta_min <= data['beta'] <= beta_max
    checks.append(f"Beta({data['beta']:.4f}) in [{beta_min}, {beta_max}]: {beta_ok}")
    
    # Gamma波检查
    gamma_max = conditions.get('gamma_max', 1)
    gamma_ok = data['gamma'] <= gamma_max
    checks.append(f"Gamma({data['gamma']:.4f}) <= {gamma_max}: {gamma_ok}")
    
    all_ok = all([theta_ok, delta_ok, alpha_ok, beta_ok, gamma_ok])
    
    print(f"     条件检查详情:")
    for check in checks:
        print(f"       - {check}")
    
    return all_ok

def analyze_n2_conditions_issues():
    """
    分析N2浅睡眠条件的问题
    """
    print("   当前N2浅睡眠条件存在的问题：")
    print("   1. Theta波范围过宽 (0.15-0.50)：")
    print("      - 正常清醒状态的Theta波也可能达到0.49")
    print("      - 应该缩小范围，更严格区分睡眠和清醒")
    print()
    print("   2. Delta波下限过低 (0.08)：")
    print("      - 清醒状态也可能有0.16的Delta波")
    print("      - 应该提高下限，确保是真正的睡眠状态")
    print()
    print("   3. Alpha波上限过高 (0.20)：")
    print("      - 真正的N2睡眠Alpha波应该更低")
    print("      - 当前条件允许过多的Alpha波存在")
    print()
    print("   4. 缺乏综合判断：")
    print("      - 应该要求Delta+Theta波的总和达到一定比例")
    print("      - 应该要求Alpha+Beta波的总和较低")

def suggest_fixes():
    """
    建议修复方案
    """
    print("   建议的N2浅睡眠条件修改：")
    print("   1. 收紧Theta波范围：0.25-0.45 (当前: 0.15-0.50)")
    print("   2. 提高Delta波下限：0.15 (当前: 0.08)")
    print("   3. 降低Alpha波上限：0.15 (当前: 0.20)")
    print("   4. 添加综合条件：")
    print("      - Delta+Theta >= 0.45 (确保低频波主导)")
    print("      - Alpha+Beta <= 0.30 (确保高频波较低)")
    print()
    print("   建议的困倦状态条件修改：")
    print("   1. 提高Theta波下限：0.45 (当前: 0.40)")
    print("   2. 降低Alpha波上限：0.15 (当前: 0.20)")
    print("   3. 添加Beta波上限：0.20")
    print()
    print("   这样可以更好地区分：")
    print("   - 清醒状态：Alpha+Beta较高，Theta较低")
    print("   - 困倦状态：Theta很高(>0.45)，但Delta较低")
    print("   - N2浅睡眠：Delta+Theta都较高，Alpha+Beta都较低")

if __name__ == "__main__":
    analyze_log_data()